package org.jiucheng.magpiebridge.manager.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.jiucheng.ioc.annotation.Component;
import org.jiucheng.ioc.annotation.Value;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * JWT处理类
 * {@link https://www.jianshu.com/p/1acfa56309b9}
 */
@Component("jwtUtil")
public class JwtUtil {
    
    private static String ISSUER = "sys_user";
    
    @Value("jwt.secret")
    private  String secret;

    /**
     * 生成token
     * 
     * @param claims
     * @param expireDatePoint  过期时间点
     * @return
     * @throws Exception 
     */
    public String genToken(Map<String, String> claims, Date expireDatePoint) throws Exception {
        //使用HMAC256进行加密
        Algorithm algorithm = Algorithm.HMAC256(secret);

        //创建jwt
        JWTCreator.Builder builder = JWT.create().
                withIssuer(ISSUER). //发行人
                withExpiresAt(expireDatePoint); //过期时间点

        //传入参数
        for (String key : claims.keySet()) {
            builder.withClaim(key, claims.get(key));
        }

        //签名加密
        return builder.sign(algorithm);
    }

    /**
     * 解密jwt
     * 
     * @param token
     * @return
     * @throws Exception  
     */
    public Map<String,String> verifyToken(String token) throws Exception {
        //使用HMAC256进行加密
        Algorithm algorithm = Algorithm.HMAC256(secret);
        //解密
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
        DecodedJWT jwt =  verifier.verify(token);
        Map<String, Claim> map = jwt.getClaims();
        Map<String, String> resultMap = new HashMap<String, String>();
        for (String key : map.keySet()) {
            resultMap.put(key, map.get(key).asString());
        }
        return resultMap;
    }
}
